<template>
  <div class="product-form-container">
    <el-card>
      <el-form :model="form" ref="formRef" label-width="100px">
        <el-form-item label="产品名称" prop="productName" :rules="{ required: true, message: '请输入产品名称', trigger: 'blur' }">
          <el-input v-model="form.productName" />
        </el-form-item>

        <el-form-item label="供应商" prop="supplierId" :rules="{ required: true, message: '请选择供应商', trigger: 'change' }">
          <el-select v-model="form.supplierId" placeholder="请选择供应商">
            <el-option
              v-for="supplier in supplierList"
              :key="supplier.id"
              :label="supplier.supplierName"
              :value="supplier.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="产品类型" prop="categoryId" :rules="{ required: true, message: '请选择产品类型', trigger: 'change' }">
          <el-select v-model="form.categoryId" placeholder="请选择">
            <el-option
              v-for="type in typeList"
              :key="type.id"
              :label="type.categoryName"
              :value="type.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="库存" prop="stock" :rules="{ required: true, message: '请输入库存数量', trigger: 'blur' }">
          <el-input v-model.number="form.stock" type="number" />
        </el-form-item>

        <el-form-item label="状态" prop="status" :rules="{ required: true, message: '请选择状态', trigger: 'change' }">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { getProductDetail, getProductTypes, addProduct, updateProduct } from '@/api/product'
import { getProviders } from '@/api/provide'
import { ElMessage } from 'element-plus'
import { onMounted, ref, defineProps, defineEmits } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const formRef = ref(null)
const form = ref({
  status: 1,  // 默认上架
  stock: 0    // 默认库存为0
})
const typeList = ref([])
const supplierList = ref([])

// 定义props
const props = defineProps({
  message: {
    type: Object,
    default: () => ({})
  }
})

// 定义emits
const emit = defineEmits(['save-success'])

// 获取所有产品类型（分页获取全部）
const fetchAllProductTypes = async () => {
  try {
    let allTypes = []
    let currentPage = 1
    let hasMore = true

    while (hasMore) {
      const res = await getProductTypes({
        pageNo: currentPage,
        pageSize: 100
      })

      allTypes = [...allTypes, ...res.data.records]

      // 检查是否还有更多数据
      if (allTypes.length >= res.data.total || res.data.records.length < 100) {
        hasMore = false
      }

      currentPage++
    }

    typeList.value = allTypes
  } catch (error) {
    ElMessage.error('获取产品类型失败: ' + error.message)
  }
}

// 获取所有供应商（分页获取全部）
const fetchAllSuppliers = async () => {
  try {
    let allSuppliers = []
    let currentPage = 1
    let hasMore = true

    while (hasMore) {
      const res = await getProviders({
        pageNo: currentPage,
        pageSize: 100
      })

      allSuppliers = [...allSuppliers, ...res.data.records]

      // 检查是否还有更多数据
      if (allSuppliers.length >= res.data.total || res.data.records.length < 100) {
        hasMore = false
      }

      currentPage++
    }

    supplierList.value = allSuppliers
  } catch (error) {
    ElMessage.error('获取供应商列表失败: ' + error.message)
  }
}

// 获取产品详情（编辑时）
const fetchDetail = async () => {
  if (props.message && props.message.id) {
    try {
      const res = await getProductDetail(props.message.id)
      // 映射字段名以匹配表单
      form.value = {
        id: res.data.id,
        productName: res.data.productName,
        supplierId: res.data.supplierId,
        categoryId: res.data.categoryId,
        status: res.data.status,
        stock: res.data.stock
      }
    } catch (error) {
      ElMessage.error('获取产品详情失败: ' + error.message)
    }
  } else if (props.message) {
    form.value = { ...props.message }
  }
}

// 保存产品
const handleSave = async () => {
  try {
    await formRef.value.validate()

    // 构造符合数据库结构的请求数据
    const requestData = {
      productName: form.value.productName,
      supplierId: form.value.supplierId,
      categoryId: form.value.categoryId,
      status: form.value.status,
      stock: form.value.stock
    }

    if (form.value.id) {
      // 编辑模式
      await updateProduct(form.value.id, requestData)
      ElMessage.success('更新成功')
    } else {
      // 新增模式
      await addProduct(requestData)
      ElMessage.success('保存成功')
    }
    emit('save-success')
  } catch (error) {
    ElMessage.error((form.value.id ? '更新失败: ' : '保存失败: ') + (error.message || '未知错误'))
  }
}

// 取消操作
const handleCancel = () => {
  router.go(-1)
}

onMounted(() => {
  fetchAllProductTypes()
  fetchAllSuppliers()
  fetchDetail()
})
</script>
